import os
import pydicom
import csv

def find_dicom_series_folders(root_dir):
    dicom_folders = []
    for dirpath, _, filenames in os.walk(root_dir):
        series_set = set()
        has_dicom = False

        for file in filenames:
            file_path = os.path.join(dirpath, file)
            try:
                dcm = pydicom.dcmread(file_path, stop_before_pixels=True, force=True)
                if hasattr(dcm, "SeriesInstanceUID"):
                    series_set.add(dcm.SeriesInstanceUID)
                    has_dicom = True
            except Exception:
                continue

        if has_dicom:
            dicom_folders.append((dirpath, len(series_set)))

    return dicom_folders

def save_multi_series_folders(root_dir, output_csv):
    dicom_folders = find_dicom_series_folders(root_dir)
    multi_series = [folder for folder, series_count in dicom_folders if series_count > 1]

    with open(output_csv, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["FolderPath"])
        for folder in multi_series:
            writer.writerow([folder])

    print(f"已完成，结果保存到 {output_csv}")


# 使用示例
root_dir = r"/media/imed/d9f520b2-6e7a-4842-af77-fba3ad2d8d27/12222"   # 修改为你的DICOM顶层文件夹
output_csv = r"multi_series_folders.csv"
save_multi_series_folders(root_dir, output_csv)